// 实现这个项目的构建任务
const {src, dest, parallel, series, watch} = require('gulp');
const del = require('del');
const loadPlugins = require('gulp-load-plugins');
const browserSync = require('browser-sync');

const plugins = loadPlugins();
const bs = browserSync.create();
const config = require('./config');

// 清除dist
const clean = () => { 
    return del(['dist', 'temp'])
}
// 编译样式
const style = () => {
    return src('src/assets/styles/*.scss', {base: 'src'})
    .pipe(plugins.sass({outputStyle: 'expanded'}))
    .pipe(dest('temp'));
}
// 编译脚本
const script = () => {
    return src('src/assets/scripts/*.js', {base: 'src'})
    .pipe(plugins.babel({presets: ['@babel/preset-env']}))
    .pipe(dest('temp'))
}
// 编译HTML
const page = () => {
    return src('src/*.html', {base: 'src'})
    .pipe(plugins.swig({data: config.data}))
    .pipe(dest('temp'))
}
// 压缩图片
const image = () => {
    return src('src/assets/images/**', {base: 'src'})
    // .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}
// 压缩字体
const font = () => {
    return src('src/assets/fonts/**', {base: 'src'})
    // .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}
// 拷贝静态资源
const extra = () => {
    return src('public/**', {base: 'public'})
    .pipe(dest('dist'))
}
// Web服务器
const serve = () => {
    watch('src/assets/styles/*.scss', style)
    watch('src/assets/scripts/*.js', script)
    watch('src/*.html', page)

    bs.init({
        notify: false,
        port: 8080,
        open: false,
        files: 'dist/**',
        server: {
            baseDir: ['temp', 'src', 'public'],
            routes: {
                '/node_modules': 'node_modules'
            }
        }
    })
}
// 合并与压缩文件
const useref = () => {
    return src('temp/*.html', {base: 'temp'})
    .pipe(plugins.useref({searchPath: ['temp', '.']}))
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
        collapseWhitespace: true,
        minifyCss: true,
        minifyJs: true
    })))
    .pipe(dest('dist'))
}
// 开发阶段编译
const start = series(parallel(style, script, page), serve);
// 打生产包
const build = series(clean, parallel(series(useref, start), extra, image, font));

module.exports = {
    start,
    build,
    clean
};